const db = require('../db')
const tool = require('../tools/tool')

module.exports = {
    async check(token, needAdmin = false) {
        let parsedData
        try {
            parsedData = JSON.parse(tool.decodeString(token))
        } catch (error) {
            throw 'token格式错误'
        }
        let re = await db.selectWithParams(`select * from user where id = ?`, [parsedData.id])
        if (re.length) {
            re = re[0]
            if (!re.token) throw '未登录'
            if (re.token !== token) throw '已在其他位置登录'
            if (needAdmin && !re.admin) throw '需要管理员权限'
            return true
        } else {
            throw '用户不存在'
        }
    },
    async genToken(id) {
        return tool.encodeString(JSON.stringify({
            id,
            time: tool.formatDate2(new Date())
        }))
    },
    async setToken(id, token) {
        await db.updateById('user', id, {
            token
        })
    },
    getSingleInfo: {
        async format(dbre) {
            if (dbre.length === 0) {
                throw '用户不存在'
            } else {
                dbre = dbre[0]
                delete dbre.password
                if (new Date() >= new Date(dbre.endTime)) {
                    dbre.vip = false
                } else {
                    dbre.vip = true
                }
                return dbre
            }
        },
        async byId(id) {
            return await this.format(await db.selectWithParams(`select * from user where id = ?`, [id]))
        },
        async byUserName(username) {
            return await this.format(await db.selectWithParams(`select * from user where username = ?`, [username]))
        },
        async byToken(token) {
            return await this.format(await db.selectWithParams(`select * from user where token = ?`, [token]))
        }
    }
}